<?php
namespace app\components\oauth2\repositories;

use app\models\OauthClient;
use app\components\oauth2\entities\ClientEntity;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;

class ClientRepository implements ClientRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getClientEntity($clientIdentifier)
    {
        /** @var  $oauthClient OauthClient*/

        $oauthClient = OauthClient::find()->where(['=','client_id',$clientIdentifier])->one();

        if($oauthClient){
            $client = new ClientEntity();

            $client->setIdentifier($clientIdentifier);
            $client->setName($oauthClient->client_name);
            $client->setRedirectUri($oauthClient->redirect_uri);
            $client->setModel($oauthClient);
            $client->setConfidential();

            return $client;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function validateClient($clientIdentifier, $clientSecret, $grantType)
    {
        $client = $this->getClientEntity($clientIdentifier);

        if(!$client)
            return false;

        if (
            $client->isConfidential() === true
            && \password_verify($clientSecret, $client->getModel()->client_secret) === false
        ) {
            return false;
        }

        return true;
    }
}